package com.vite.file.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.vite.common.annotation.Log;
import com.vite.common.core.controller.BaseController;
import com.vite.common.core.domain.AjaxResult;
import com.vite.common.core.page.TableDataInfo;
import com.vite.common.enums.BusinessType;
import com.vite.common.exception.ServiceException;
import com.vite.common.utils.StringUtils;
import com.vite.file.domain.FileDetail;
import com.vite.file.service.FileDetailService;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 文件信息Controller
 */
@RestController
@RequestMapping("/system/file")
@RequiredArgsConstructor
public class FileController extends BaseController
{

    private final FileDetailService fileDetailService;

    private final FileStorageService fileStorageService;


    /**
     * 文件列表
     */
    @PreAuthorize("@ss.hasPermission('system:file:list')")
    @GetMapping("/list")
    public TableDataInfo list(FileDetail file)
    {
        startPage();
        QueryWrapper<FileDetail> queryWrapper = Wrappers.query();
        String realName = file.getOriginalFilename();
        if (StringUtils.isNotEmpty(realName))
        {
            queryWrapper.like(FileDetail.COL_ORIGINAL_FILENAME, realName);
        }
        List<FileDetail> list = fileDetailService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 删除文件
     */
    @PreAuthorize("@ss.hasPermission('system:file:remove')")
    @Log(title = "文件记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@NonNull @PathVariable("id") String id) throws Exception
    {
        FileDetail fileDetail = fileDetailService.getById(id);
        if (fileDetail == null) {
            throw new ServiceException("文件不存在或已被删除");
        }
        FileInfo fileInfo = fileDetailService.toFileInfo(fileDetail);
        boolean delete = fileStorageService.delete(fileInfo);
        return toAjax(delete);
    }

}